package com.cropdoctor.service.impl;

import com.cropdoctor.model.po.SysPermissionPo;
import com.cropdoctor.model.po.SysUserPo;
import com.cropdoctor.service.SysPermissionService;
import com.cropdoctor.service.SysRoleService;
import com.cropdoctor.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private SysRoleService sysRoleService;


    @Override
    //要想进入该方法 必须是POST请求 路径为'auth/form/login' 并且请求体中必须携带以"username"为key的参数 并且必须是以表单提交的方式
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //需要构造出 org.springframework.security.core.userdetails.User 对象并返回
        //校验验证码等操作....

        if(!StringUtils.isNotBlank(username)){
            throw new RuntimeException("用户不能为空");
        }
        SysUserPo userEntity = sysUserService.selectByName(username);
        if(userEntity==null){
            throw new RuntimeException("用户不存在");
        }
        List<GrantedAuthority> grantedAuthorities  = new ArrayList<>();
        //获取该用户所拥有的权限
        List<SysPermissionPo> permissionList = sysPermissionService.selectListByUser(userEntity.getId());


        //角色和权限共用GrantedAuthority接口，唯一的不同角色就是多了个前缀"ROLE_"
        // 声明用户授权
        permissionList.forEach(permission ->{
            //基于权限控制
            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getPermissionCode()));
        });

        /*由于CustomizeAccessDecisionManager中的decide方法只是基于权限判断 因此这里暂时不需要设置角色*/
        //获取用户所有角色
//        List<SysRolePo> roleList = sysRoleService.selectByUser(userEntity.getId());

        // 声明用户角色
//        roleList.forEach(role ->{
//            //基于角色控制
//            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleCode()));
//        });

        //封装后的UserDetails
        User user = new User(userEntity.getAccount(),
                userEntity.getPassword(),
                userEntity.getEnabled() == 1,
                true,
                true,
                true,
                grantedAuthorities);

        return user;
    }

}

